﻿using System;
using System.Buffers.Binary;

namespace WholeSlideImageLibrary.Formats.Dmetrix
{
    internal struct DmetrixFileTileIndex
    {
        /// <summary>
        /// Layer where the tile belongs.
        /// </summary>
        public short Layer { readonly get; private set; }
        /// <summary>
        /// Column in this layer.
        /// </summary>
        public int Column { readonly get; private set; }
        /// <summary>
        /// Row in this layer.
        /// </summary>
        public int Row { readonly get; private set; }
        /// <summary>
        /// Start position after file header.
        /// </summary>
        public long StartPosition { readonly get; private set; }
        /// <summary>
        /// Size of this tile.
        /// </summary>
        public int Size { readonly get; private set; }

        public const int MarshalStructureSize = 22;

        public static bool TryParse(ReadOnlySpan<byte> buffer, out DmetrixFileTileIndex data)
        {
            data = default;
            if (buffer.Length < MarshalStructureSize)
            {
                return false;
            }
            data.Layer = BinaryPrimitives.ReadInt16LittleEndian(buffer);
            data.Column = BinaryPrimitives.ReadInt32LittleEndian(buffer.Slice(2));
            data.Row = BinaryPrimitives.ReadInt32LittleEndian(buffer.Slice(6));
            data.StartPosition = BinaryPrimitives.ReadInt64LittleEndian(buffer.Slice(10));
            data.Size = BinaryPrimitives.ReadInt32LittleEndian(buffer.Slice(18));
            return true;
        }
    }
}
